<?php

/**
 * @author      Nguyen Duc Thuan <me@ndthuan.com>
 * @copyright   Copyright (c) 2009 Nguyen Duc Thuan <me@ndthuan.com>
 * @version     $Id: Language.php 12 2009-11-03 03:17:46Z thuan.nguyen $
 */

class Fete_Language
{
    protected $_phrases = array();

    static protected $_instance = null;

    /**
     *
     * @return Fete_Language
     */
    static public function getInstance()
    {
        if (null === self::$_instance) {
            self::$_instance = new self();
        }

        return self::$_instance;
    }

    /**
     *
     * @param string $langFile
     * @return Fete_Language
     */
    public function &loadFile($langFile, $type = 'array')
    {
        switch ($type)
        {
            case 'ini':
                $phrases = parse_ini_file($langFile);
                break;

            case 'xml':
                /**
                 * @todo handle XML data file
                 */
                $phrases = array();
                break;

            default:
                $phrases = require $langFile;
                break;
        }

        if (is_array($phrases)) {
            $this->_phrases = array_merge($this->_phrases, $phrases);
        }

        return $this;
    }

    public function getAllPhrases()
    {
        return $this->_phrases;
    }

    public function getPhrase($key)
    {
        return isset($this->_phrases[$key]) ? $this->_phrases[$key] : null;
    }

    public function exists($key)
    {
        return isset($this->_phrases[$key]);
    }

    protected function __construct() {}
    private function __clone() {}

    public function __isset($key)
    {
        return isset($this->_phrases[$key]);
    }

    public function __get($key) {
        return $this->getPhrase($key);
    }
}

/**
 * Utility to quickly get language phrase
 * @param string $key
 */
function fl($key)
{
    $args = func_get_args();
    $lang = Fete_Language::getInstance();

    if ($lang->exists($key)) {
        $args[0] = $lang->getPhrase($key);
    }

    return call_user_func_array('sprintf', $args);
}